import logging
import os
import socket
from datetime import datetime


def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = s.getsockname()[0]
    s.close()
    return ip


class IPBasedFileHandler(logging.FileHandler):
    def __init__(self, base_log_dir, mode='a', encoding=None, delay=False):
        self.base_log_dir = base_log_dir
        ip = get_local_ip()
        log_file_path = os.path.join(self.base_log_dir, f'material_center_{datetime.now().strftime("%Y-%m-%d")}_{ip}.log')
        super().__init__(filename=log_file_path, mode=mode, encoding=encoding, delay=delay)